(defun half (n)
  (floor (/ n 2)))


(defun factors (n)
  (let ((fact nil))
    (dotimes (i (half n) fact)
      (if (zerop (mod n (1+ i))) 
	  (setq fact (cons (1+ i) fact))))))

(defun sum-fact (n)
  (reduce #'+ (list-divisors n)))

(defun amicablep2 (n)
  (let ((m (sum-fact n)))
    (and (< n m)
	 (= n (sum-fact m)))))

(defun amicablep (n)
  (let ((m (sum-fact n)))
    (and (not (= m n))
	 (= n (sum-fact m)))))

(defun collect-amicable (n)
  (loop for i from 1 to n when (amicablep i) collect i))

(defun sum-amicable (n)
  (reduce #'+ (collect-amicable n)))

(defun list-divisors (n)
  (loop for i from 1 to (sqrt n)
        when (= (mod n i) 0)
          collect i
          and unless (= i (/ n i))
                collect (/ n i)))